package com.conv.shop.business.controller;

import com.conv.shop.business.domain.Product;
import com.conv.shop.business.req.InventoryChangeReq;
import com.conv.shop.business.req.ProductReq;
import com.conv.shop.business.req.ProductSearchByNameReq;
import com.conv.shop.business.req.UpdateProductReq;
import com.conv.shop.business.service.ProductService;
import com.conv.shop.business.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService productService;

    /**
     * 查询所有商品
      * @param pageNum
     * @param pageSize
     * @param productName
     * @return List<Product>
     */
    @PostMapping("/productList")
    public List<Product> getList(@RequestBody int pageNum, int pageSize, String productName) {
        return this.productService.getProductList(pageNum,pageSize,productName);
    }

    /**
     * 商品详情列表
     * @param product
     * @return product
     */
    @PostMapping("/getProductDetail")
    public Product getProductDetail(@RequestBody Product product){
        return productService.getProductById(product);
    }

    /**
     * 新增商品
     * @param productName
     * @param categoryId
     * @param price
     * @param description
     * @param stockQuantity
     * @param file
     * @param request
     * @return String
     */
    @PostMapping("/save")
    public ResponseEntity<String> save(@RequestParam String productName,
                                       @RequestParam int categoryId,
                                       @RequestParam double price,
                                       @RequestParam String description,
                                       @RequestParam int stockQuantity,
                                       @RequestParam("image") MultipartFile file,
                                       HttpServletRequest request) {
        String token = request.getHeader("token");
        int consumerId = Integer.parseInt(JwtUtil.getUserNameByToken(token));
        ProductReq productReq = new ProductReq();
        productReq.setProductName(productName);
        productReq.setCategoryId(categoryId);
        productReq.setPrice(price);
        productReq.setDescription(description);
        productReq.setStockQuantity(stockQuantity);
        String fileName = file.getOriginalFilename();

        // 定义文件保存路径
        Path path = Paths.get("userweb/images" + File.separator + fileName);

        // 保存文件到指定路径
        try {
            Files.write(path, file.getBytes());

            // 更新ProductReq中的图片路径或URL
            productReq.setImageUrl("images" + File.separator + fileName);

            // 保存ProductReq到数据库
            if (productService.save(productReq, consumerId)) {
                return ResponseEntity.ok("商品添加成功");
            } else {
                // 清理已上传的文件
                Files.delete(path);
                return ResponseEntity.badRequest().body("商品添加失败");
            }
        } catch (IOException e) {
            // 处理文件保存异常
            e.printStackTrace();
            return ResponseEntity.badRequest().body("文件保存失败：" + e.getMessage());
        }
    }

    /**
     *  商品搜索
     * @param productByNameReq
     * @return List<Product>
     */
    @PostMapping("/searchProduct")
    public List<Product> searchProduct(@RequestBody ProductSearchByNameReq productByNameReq) {
        return productService.searchProduct(productByNameReq);
    }

    /**
     * 商品类别查询
      * @param categoryId
     * @return List<Product>
     */
    @PostMapping("searchProductByCategory")
    public List<Product> searchProductByCategory(@Validated @RequestBody Integer categoryId) {
        return productService.getProductListbyCategory(categoryId);
    }

    /**
     * 更新商品
      * @param updateProductReq
     * @return boolean
     */
    @PostMapping("/update")
    public boolean update(@Validated @RequestBody UpdateProductReq updateProductReq) {
        return productService.update(updateProductReq.getProductId(), updateProductReq.getProductReq());
    }


    /**
     * 商品下架
      * @param id
     * @return boolean
     */
    @PostMapping("/unpublishProduct")
    public boolean delete(@Validated @RequestBody int id) {
        return productService.unpublishProduct(id);
    }

    /**
     * 库存管理
      * @param request
     * @return boolean
     */
    @PostMapping("/manageInventory")
    public boolean manageInventory(@Validated @RequestBody InventoryChangeReq request) {
        return productService.manageInventory(request.getId(), request.getNum(),request.getOption());
    }

    /**
     * 带分页查询
     * @param request
     * @param pageNum
     * @param pageSize
     * @param productName
     * @return List<Product>
     */
    @RequestMapping("/productListByPage")
    public List<Product> getList(HttpServletRequest request,
                          @RequestParam(defaultValue = "1") int pageNum,
                          @RequestParam(defaultValue = "12") int pageSize,
                          @RequestParam(defaultValue = "") String productName
                                ) {
        return productService.getProductList(pageNum,pageSize,productName);
    }

    /**
     * 商铺按照页码查询商品列表
     * @param request
     * @param pageNum
     * @return List<Product>
     */
    @GetMapping("/getProductByStore/{pageNum}")
    public List<Product> getProductByStore(HttpServletRequest request, @PathVariable String pageNum) {
        String token = request.getHeader("token");
        if (token == null){
            return null;
        }
        if(!JwtUtil.validate(token)){
            return null;
        }
        int consumerId = Integer.parseInt(JwtUtil.getUserNameByToken(token));
        return productService.getProductByStore(consumerId);
    }

    /**
     *  删除商品
     * @param id
     * @param request
     * @return boolean
     */
    @DeleteMapping("/delete/{id}")
    public ResponseEntity<String> delete(@PathVariable("id") String id, HttpServletRequest request) {
        String token = request.getHeader("token");
        boolean ok = JwtUtil.validate(token);
        if (!ok){
            return ResponseEntity.badRequest().body("非法用户");
        }
        if (productService.delete(Integer.parseInt(id))) {
            return ResponseEntity.ok().body("删除成功");
        }
        return ResponseEntity.notFound().build();
    }
}
